//
//  HMCycleImageView.m
//  Pods
//
//  Created by WangYong on 2017/9/10.
//
//

#import "HMCycleImageView.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface HMCycleImageItemViewCell : UICollectionViewCell

@property(strong,nonatomic) UIImageView *imageView;

@end

@implementation HMCycleImageItemViewCell

- (instancetype)init{
    self = [super init];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

//初始化构建界面
- (void)setup{
    self.imageView = [UIImageView new];
    self.imageView.contentMode = UIViewContentModeRedraw;

    [self.contentView addSubview:self.imageView];

    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];
}

@end

@interface HMCycleImageView ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>

@property (strong,nonatomic) UICollectionView *collectionView;

@property (strong,nonatomic) UIPageControl *pageControl;

@end

@implementation HMCycleImageView
{
    NSInteger _count;
    NSTimer *_timer;
}

- (void)removeFromSuperview{
    [super removeFromSuperview];

    //清除定时器,避免定时器和View之间的循环引用
    [self clearTimer];
}

#pragma mark - 懒加载控件
- (UICollectionView *)collectionView{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [UICollectionViewFlowLayout new];

        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];

        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[HMCycleImageItemViewCell class] forCellWithReuseIdentifier:@"CELL"];

        _collectionView.delegate = self;
        _collectionView.dataSource = self;

        [self addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];

    }
    return _collectionView;
}

- (UIPageControl *)pageControl{
    if (_pageControl == nil) {
        _pageControl = [UIPageControl new];

        [self addSubview:_pageControl];

        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(30);
        }];
    }
    return _pageControl;
}

//刷新
- (void)reloadData{
    if (self.datasource && [self.datasource respondsToSelector:@selector(numberOfItemsInCycleImageView:)]) {
        _count = [self.datasource numberOfItemsInCycleImageView:self];
    }

    [self.collectionView reloadData];
    [self layoutIfNeeded];

    [self.pageControl setPageIndicatorTintColor:[UIColor darkGrayColor]];

    [self.pageControl setCurrentPageIndicatorTintColor:self.mainColor ? self.mainColor : [UIColor orangeColor]];

    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = _count;
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.frame.size.width*_count*100, 0) animated:YES];

    //启动定时器
    [self startTimer];
}

#pragma mark - 定时器 -
//作用: 自动滚动到下一张
- (void )doTimer{
    CGPoint offset = CGPointMake(self.collectionView.contentOffset.x + self.collectionView.frame.size.width, 0);

    [self.collectionView setContentOffset:offset animated:YES];
    self.pageControl.currentPage = ((int)(offset.x / self.collectionView.frame.size.width))%_count;
}

//启动定时器
- (void)startTimer{
    [self clearTimer];

    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                              target:self
                                            selector:@selector(doTimer)
                                            userInfo:nil
                                             repeats:YES];
}

//清除定时器
- (void)clearTimer{

    if (_timer) {
        if (_timer.isValid) {
            [_timer invalidate];
        }
        _timer = nil;
    }

}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _count * 10000;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HMCycleImageItemViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    if (self.datasource && [self.datasource respondsToSelector:@selector(cycleImageView:itemUrlAtIndex:)]) {
        NSInteger inx = indexPath.row % _count;

        NSURL *url = [self.datasource cycleImageView:self itemUrlAtIndex:inx];

        if (self.placeholderImage == nil) {
            [cell.imageView sd_setImageWithURL:url];
        }else {
            [cell.imageView sd_setImageWithURL:url placeholderImage:self.placeholderImage];
        }
    }
    return  cell;
}

#pragma mark - UICollectionViewDelegate -
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.frame.size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsZero;

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

#pragma mark - UIScrollViewDelegate - 
//将要开始滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    //将定时器清除
    [self clearTimer];
}

//停止
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    //pageControl变化
    self.pageControl.currentPage = ((int)(scrollView.contentOffset.x / scrollView.frame.size.width)%_count);

    //启动定时器
    [self startTimer];
}


@end
